//
//  NewsTableViewController.m
//  FootBallTest_huang
//
//  Created by lanou3g on 15/5/30.
//  Copyright (c) 2015年 lanou3g.com. All rights reserved.
//

#import "NewsTableViewController.h"
#import "NewsTableViewCell.h"
#import "AFHTTPRequestOperationManager.h"
#import "NewsModle.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "NewsDetailsTableViewController.h"
#import "NewsaDetailsViewController.h"

@interface NewsTableViewController ()

@end

@implementation NewsTableViewController

- (instancetype)initWithStyle:(UITableViewStyle)style useHomePage:(NSString*)homePage refreshWeb:(NSString*)refreshWeb detailWeb:(NSString*)detailWeb{
    
    
    if (self = [super initWithStyle:style]) {
        
        self.homePageWeb = homePage;//主页网址
        self.refreshWeb =refreshWeb;//刷新网址
        self.detailWeb = detailWeb;//详情网址
        
        
    }
    
    
    
    return self;
    
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
//    利用第三方AFNetWorking解析数据
    [self stringWithFormat:self.homePageWeb];
//
//    注册cell对象(xib类型的)
    [self.tableView registerNib:[UINib nibWithNibName:@"NewsTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"myCell"];
//
//    集成刷新空间
    [self setupRefresh];
    
    [self performSelector:@selector(endRefreshingIFNO) withObject:nil afterDelay:2.0];
    

}

//当没有网络的时候。不会一直刷新
- (void)endRefreshingIFNO
{
    [self.tableView headerEndRefreshing];
}


//利用第三方AFNetWorking解析数据
- (void)stringWithFormat:(NSString *)url
{
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
    __weak NewsTableViewController * newsTVC = self;
  
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
       
            
        NSDictionary * BigDic =responseObject;//responseObject相当于data
        
        
        
        NSMutableDictionary * dic = [BigDic objectForKey:@"result"];
        if (dic.count != 0) {
            
        
        
        NSMutableArray * array = [dic objectForKey:@"data"];
        
        self.modleArray = [NSMutableArray array];
        
        for (NSMutableDictionary * smallDic in array) {
            
            NewsModle * newmodle = [[NewsModle alloc] init];
            [newmodle setValuesForKeysWithDictionary:smallDic];
            [newsTVC.modleArray addObject:newmodle];
            
        }
        [newsTVC.tableView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        
    }];
    
}

- (void)setupRefresh
{
    //1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    // dateKey用于存储刷新时间，可以保证不同界面拥有不同的刷新时间
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing) dateKey:@"table"];
    
#pragma 自动刷新(-——进入程序就下拉刷新)
    [self.tableView headerBeginRefreshing];
    
    //2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    //设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.tableView.headerPullToRefreshText = @"下拉可以刷新了";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在刷新";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"正在努力刷新";
    
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{

    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
    __weak NewsTableViewController * newsTVC = self;
   
    NSString * url = [NSString stringWithFormat:@"%@",self.homePageWeb];
    
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        if (responseObject == nil) {
//            return ;
//        }
        if (responseObject) {
            
        
        NSDictionary * BigDic =responseObject;//responseObject相当于data
        NSMutableDictionary * dic = [BigDic objectForKey:@"result"];
            
            if (dic.count !=0) {
                
            
        NSMutableArray * array = [dic objectForKey:@"data"];
        NSMutableArray * modleArray = [NSMutableArray array];
        
        for (NSMutableDictionary * smallDic in array) {
            NewsModle * newsmodle = [[NewsModle alloc] init];
            [newsmodle setValuesForKeysWithDictionary:smallDic];
            [modleArray addObject:newsmodle];
            
        }
        newsTVC.modleArray = modleArray;
        [newsTVC.tableView reloadData];
        [newsTVC.tableView headerEndRefreshing];
         }
       }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


- (void)footerRereshing
{
    
    
    NewsModle * newModle = _modleArray.lastObject;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
    __weak NewsTableViewController * newsTVC = self;

    NSString * url = [NSString stringWithFormat:@"%@%@",self.refreshWeb,newModle.nid];
    
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary * BigDic =responseObject;//responseObject相当于data
        NSMutableDictionary * dic = [BigDic objectForKey:@"result"];
        NSMutableArray * array = [dic objectForKey:@"data"];
        NSMutableArray * modleArray = [NSMutableArray array];

        
        for (NSMutableDictionary * smallDic in array) {
            
            NewsModle * newsmodle = [[NewsModle alloc] init];
            [newsmodle setValuesForKeysWithDictionary:smallDic];
            [modleArray addObject:newsmodle];
            
        }
        
        [newsTVC.modleArray addObjectsFromArray:modleArray];
        [newsTVC.tableView reloadData];
        [newsTVC.tableView footerEndRefreshing];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        
    }];
    
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    
    return _modleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"myCell"];
    NewsModle * newmodle = _modleArray[indexPath.row];
    cell.title.text = newmodle.title;
    cell.summary.text = newmodle.summary;
    cell.replies.text = newmodle.replies;
    
    //利用第三方(SDWibImage)下载图片
    [cell.image sd_setImageWithURL:[NSURL URLWithString:newmodle.img] placeholderImage:[UIImage imageNamed:@"placeHold"]];
    

    
    return cell;
}




#pragma mark---计算文本高度
- (CGFloat)textLabelHeight:(NSString *)text
{
    
    CGSize size = CGSizeMake(self.view.frame.size.width, 10000000);
    NSDictionary * dic = @{NSFontAttributeName:[UIFont systemFontOfSize:16.0]};
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:dic context:nil];
    return rect.size.height;
}


#pragma mark---设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        NewsModle * newmodle = _modleArray[indexPath.row];
   
        CGFloat heingt = [self textLabelHeight:newmodle.summary];
    
        if (heingt+31 < 105) {
            return 105;
        }
   
    return heingt+31;
    
}




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    NewsaDetailsViewController * newsDtailsVC = [[NewsaDetailsViewController alloc] init];
    
    NewsModle * newsModle = _modleArray[indexPath.row];
    
    newsDtailsVC.newsModle = newsModle;
    

    
    newsDtailsVC.replies = newsModle.replies;
    
    newsDtailsVC.newsModle.detailWeb = self.detailWeb;
   
    [self.navigationController pushViewController:newsDtailsVC animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Table view delegate

// In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here, for example:
    // Create the next view controller.
    <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
    
    // Pass the selected object to the new view controller.
    
    // Push the view controller.
    [self.navigationController pushViewController:detailViewController animated:YES];
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
